package com.bykj.property.config.shiro;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bykj.property.sys.dao.SysUserDao;
import com.bykj.property.model.SysUser;
import com.bykj.property.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import com.bykj.property.model.SysRole;
import com.bykj.property.model.SysMenu;

/**
* @author yiming
* @title: MyShiroRealm
* @projectName property
* @description: TODO
* @date 2019/6/1117:30
*/
@Slf4j
public class MyShiroRealm extends AuthorizingRealm {
//用于用户查询
@Autowired
@Lazy
private SysUserDao sysUserDao;

//角色权限和对应权限添加
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取登录用户名
String name= (String) principalCollection.getPrimaryPrincipal();
//查询用户名称

SysUser user = sysUserDao.getByUsername(name);
log.info("+++++++++", JSON.toJSONString(user));
//添加角色和权限
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
for (SysRole role:user.getSysRoles()) {
//添加角色
simpleAuthorizationInfo.addRole(role.getName());
for (SysMenu menu:role.getSysMenus()) {
//添加权限
simpleAuthorizationInfo.addStringPermission(menu.getName());
}
}
return simpleAuthorizationInfo;
}

//用户认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//加这一步的目的是在Post请求的时候会先进认证，然后在到请求
if (authenticationToken.getPrincipal() == null) {
return null;
}
//获取用户信息
String name = authenticationToken.getPrincipal().toString();
SysUser user = sysUserDao.getByUsername(name);
if (user == null) {
//这里返回后会报出对应异常
return null;
} else {
//这里验证authenticationToken和simpleAuthenticationInfo的信息
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, user.getPassword().toString(), getName());
simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
return simpleAuthenticationInfo;
}
}
}
